#include "efect.h"

Efect::Efect()
{
	dead = 1;
	actual_frame = 0;
}

Efect::~Efect()
{
	//dtor
}

i32 Efect::Set ( string v_resource, i32 duration_ms, i32 ms_per_frame, i32 x, i32 y )
{
	graph = ( Graphics * ) RES->GET ( v_resource );
//	graph->spr.frames[actual_frame].surface[0]->format->Amask = 0xFF000000;
//	SDL_SetAlpha ( graph->spr.frames[actual_frame].surface[0], SDL_SRCALPHA | SDL_SRCCOLORKEY, 0xFF );
	px = x;
	py = y;
	frame_interval = ms_per_frame;
	callbackV1 clb;

	if ( duration_ms == -1 )
	{
		mode = FX_MODE_ONCE;
	}
	else
	{
		mode = FX_MODE_LOOP;
		clb.bind ( this, &Efect::killme );
		efect_duration.doOnce ( duration_ms, clb );
	}

	clb.bind ( this, &Efect::switch_frame );
	frame_keeper.doPeriodicaly ( ms_per_frame, clb );
	return 1;
}

i32 Efect::Start()
{
	dead = 0;
	frame_keeper.start();

	if ( mode == FX_MODE_LOOP )
	{
		efect_duration.start();
	}
	actual_frame = 0;

	return 1;
}

i32 Efect::Stop()
{
	dead = 1;
	frame_keeper.reset();
	efect_duration.reset();
	return 1;
}

//i32 Efect::Move ( i32 x, i32 y )
//{
//	px = x;
//	py = y;
//	return 1;
//}

i32 Efect::ChangeDuration ( i32 duration_ms )
{
	if ( mode == FX_MODE_ONCE )
	{
		return 0;
	}

	callbackV1 clb;
	clb.bind ( this, &Efect::killme );
	efect_duration.doOnce ( duration_ms, clb );
	return 1;
}

void Efect::killme()
{
	dead = 1;
	efect_duration.reset();
	frame_keeper.reset();
}

void Efect::switch_frame()
{
	actual_frame ++;

	if ( actual_frame > ((i32)graph->spr.frames.size() - 1 )) {
		if ( mode == FX_MODE_ONCE )
		{
			killme();
			return;
		}

		actual_frame = 0;
	}
}

i32 Efect::Render()
{
	if ( dead ) {
		return 1;
	}

	SDL_Rect r;
	r.x = px;
	r.y = py;
//	graph->spr.frames[actual_frame].surface[0]->format->Amask = 0xFF000000;
//	SDL_SetAlpha ( graph->spr.frames[actual_frame].surface[0], SDL_SRCALPHA | SDL_SRCCOLORKEY, 0xFF );
	SDL_BlitSurface ( graph->spr.frames[actual_frame].surface[0], 0, g_screen, &r );
	return 1;
}












